package top.xcxdl.rural.controller.publics;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.*;
import com.aliyun.oss.model.ObjectMetadata;
import com.coremedia.iso.IsoFile;
import com.googlecode.mp4parser.DataSource;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import top.xcxdl.rural.common.Res;
import top.xcxdl.rural.config.consts.OssConst;
import top.xcxdl.rural.entity.RuralResource;
import top.xcxdl.rural.service.IRuralResourceService;
import top.xcxdl.rural.utils.FileUtil;
import top.xcxdl.rural.utils.JWTUtils;
import top.xcxdl.rural.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.Inet4Address;
import java.util.UUID;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Ding
 * @create 2022/1/27 12:30
 */
@Log4j2
@Api("文件上传")
@RestController
@CrossOrigin
@RequestMapping("/public")
public class PublicController {

    @Resource
    private IRuralResourceService service;

    /**
     * 文件上传
     *
     * @param file     文件
     * @param request  请求
     * @param response 响应
     * @return 文件路径
     * @throws IOException 异常
     */
    @PostMapping("/upload")
    @ResponseBody
    public JSONObject uploadFile(@RequestParam MultipartFile file,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws IOException, UnsupportedAudioFileException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        JSONObject jsonObject = new JSONObject();
        //创建随机文件名
        String filename = UUID.randomUUID().toString().replaceAll("-", "");
        //文件后缀
        String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //新文件名
        String newFileName = filename + ext;
        //获取上传的输入流
        InputStream inputStream = file.getInputStream();
        //设置访问地址是默认是预览图片
        ObjectMetadata meta = new ObjectMetadata();
        //设置文件的类型
        long videoLength = 0;
        if (".mp4".equals(ext)) {
            //视频格式
            meta.setContentType("video/mp4");
            videoLength = FileUtil.getVideoDuration(file,filename,ext);
        } else {
            //图片格式
            meta.setContentType("image/jpg");
        }
        // 创建OSSClient实例
        OSS oss = new OSSClientBuilder().build(OssConst.END_POINT, OssConst.KEY_ID, OssConst.KEY_SECRET);
        try {
            //执行上传
            String fileUrl = OssConst.FILE_HOST + "/" + newFileName;
            oss.putObject(OssConst.BUCKET_NAME, fileUrl, inputStream, meta);
        } catch (OSSException | ClientException e) {
            log.error("{}{}（ID为{}）进行了一次失败的文件上传，{}", JWTUtils.getAuthorTypeName(),JWTUtils.getAuthorName(),JWTUtils.getAuthorId(),e.getMessage());
        } finally {
            oss.shutdown();
        }
        //资源访问全路径
        String allUrl = "https://" + OssConst.BUCKET_NAME + "." + OssConst.END_POINT + "/" + "resource" + "/" + newFileName;

        RuralResource ruralResource = new RuralResource();
        ruralResource.setUrl(newFileName);
        if (service.toAddItem(ruralResource) > 0) {
            jsonObject.put("stat", 200);
            jsonObject.put("url", allUrl);
            jsonObject.put("resourceId", ruralResource.getRId());
            if (videoLength > 0) {
                jsonObject.put("videoLength", videoLength);
            }
            log.info("{}{}（ID为{}）进行了一次文件上传，文件大小{}b", JWTUtils.getAuthorTypeName(),JWTUtils.getAuthorName(),JWTUtils.getAuthorId(),file.getSize());
        } else {
            jsonObject.put("stat", 500);
            log.error("{}{}（ID为{}）进行了一次失败的文件上传，若OSS传输成功，则原因可能是链接入库失败", JWTUtils.getAuthorTypeName(),JWTUtils.getAuthorName(),JWTUtils.getAuthorId());
        }
        return jsonObject;
    }
}
